<template>
  <div class="task-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="searchForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="任务名称">
              <el-input v-model="searchForm.taskName" placeholder="请输入任务名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务类型">
              <el-select v-model="searchForm.taskType" placeholder="请选择任务类型" clearable>
                <el-option label="数据同步" value="SYNC" />
                <el-option label="数据处理" value="PROCESS" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                <el-option label="运行中" value="RUNNING" />
                <el-option label="已完成" value="COMPLETED" />
                <el-option label="失败" value="FAILED" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="text-align: right;">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon>
        新建任务
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-card shadow="never">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="taskName" label="任务名称" min-width="180" />
        <el-table-column prop="taskType" label="任务类型" width="120">
          <template #default="{ row }">
            {{ formatTaskType(row.taskType) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)">
              {{ formatStatus(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <task-dialog
      v-model="dialogVisible"
      :dialog-type="dialogType"
      :current-data="currentData"
      @refresh="getList"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import TaskDialog from './components/TaskDialog.vue'
import { taskApi, type Task } from '@/api/task'

// 搜索表单
const searchForm = reactive({
  taskName: '',
  taskType: '',
  status: ''
})

// 表格数据
const tableData = ref<Task[]>([])
const loading = ref(false)

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('create')
const currentData = ref<Partial<Task>>({})

// 格式化任务类型
const formatTaskType = (type: string) => {
  const types: Record<string, string> = {
    SYNC: '数据同步',
    PROCESS: '数据处理'
  }
  return types[type] || type
}

// 格式化状态
const formatStatus = (status: string) => {
  const statusMap: Record<string, string> = {
    RUNNING: '运行中',
    COMPLETED: '已完成',
    FAILED: '失败'
  }
  return statusMap[status] || status
}

// 状态标签类型
const statusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    RUNNING: 'warning',
    COMPLETED: 'success',
    FAILED: 'danger'
  }
  return typeMap[status] || ''
}

// 获取任务列表
const getList = async () => {
  loading.value = true
  try {
    const { data } = await taskApi.fetchTasks({ 
      ...searchForm,
      current: pagination.current,
      size: pagination.size
    })
    tableData.value = data.list
    pagination.total = data.total
  } catch (error) {
    ElMessage.error('获取任务列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.taskName = ''
  searchForm.taskType = ''
  searchForm.status = ''
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  getList()
}

// 当前页变化
const handleCurrentChange = (current: number) => {
  pagination.current = current
  getList()
}

// 新增任务
const handleCreate = () => {
  dialogType.value = 'create'
  currentData.value = {}
  dialogVisible.value = true
}

// 编辑任务
const handleEdit = (row: Task) => {
  dialogType.value = 'edit'
  currentData.value = { ...row }
  dialogVisible.value = true
}

// 删除任务
const handleDelete = (row: Task) => {
  ElMessageBox.confirm('确认删除该任务吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const loading = ElLoading.service({
      lock: true,
      text: '删除中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    try {
      await taskApi.deleteTask(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      ElMessage.error('删除失败')
      console.error(error)
    } finally {
      loading.close()
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.task-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.operation-area {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
